package com.tieba.service.impl;


import com.tieba.mapper.UserMapper;
import com.tieba.pojo.Password;
import com.tieba.pojo.User;
import com.tieba.service.UserService;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> list() {
        return userMapper.list();
    }

    @Override
    public User getById(Integer id){
        return userMapper.getById(id);
    }

    @Override
    public void add(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
    }

    @Override
    public void delete(List<Integer> ids) {
        userMapper.delete(ids);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public User login(User user) {
        return userMapper.getByUsernameAndPassword(user);
    }

    @Override
    public User register(User user) {
        //先看数据库中是否已经存在该用户
        User regUser = userMapper.getByUsername(user);
        if (regUser != null) {
            return regUser;
        }
        user.setPermission((short)1);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
        return null;
    }

    @Override
    public Boolean updatePassword(Password password) {
        User user = userMapper.getById(password.getUserId());
        if (user != null) {
            if (user.getPassword().equals(password.getOldPassword())){
                user.setPassword(password.getNewPassword());
                userMapper.update(user);
                return true;
            }
            else return false;
        }

        return false;
    }

}
